package com.example.myapplication.fragment;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.example.myapplication.App;
import com.example.myapplication.R;
import com.example.myapplication.dao.UserDao;
import com.example.myapplication.database.GreenDaoManager;
import com.example.myapplication.databinding.FragmentMeBinding;
import com.example.myapplication.model.MeModel;
import com.example.myapplication.ui.user.GuanzhuListActivity;
import com.example.myapplication.ui.user.OrderListActivity;
import com.example.myapplication.ui.user.RecordActivity;
import com.example.myapplication.ui.user.ShopAddressListActivity;
import com.example.myapplication.ui.user.UserInfoActivity;
import com.example.myapplication.utils.ImageEngine;
import com.example.myapplication.utils.Utils;
import com.example.myapplication.widget.MenuOptionsView;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.huantansheng.easyphotos.utils.permission.PermissionUtil;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;

import java.util.ArrayList;

import cn.project.base.baseui.BaseNormalFragment;
public class UserMeFragment extends BaseNormalFragment<FragmentMeBinding> {

    // 用户信息模型
    MeModel meModel;
    // 用户数据访问对象
    UserDao userDao;

    // 获取布局ID
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }

    // 初始化数据
    @Override
    protected void initData() {
        userDao = GreenDaoManager.getmInstance().getDaoSession().getUserDao();
        meModel = new ViewModelProvider(getActivity()).get(MeModel.class);
        if (App.getInstance().user != null) {
            mBinding.tvName.setText(App.getInstance().user.getName());
            if (!TextUtils.isEmpty(App.getInstance().user.getHead_url())) {
                Glide.with(getActivity()).load(App.getInstance().user.getHead_url()).into(mBinding.imageHead);
            }
        }

        // 浏览记录
        mBinding.icLiulan.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), RecordActivity.class));
            }
        });

        mBinding.icUser.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
            }
        });
        mBinding.icGuanzhu.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), GuanzhuListActivity.class));
            }
        });
        mBinding.icPhone.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + "023666666"));
                startActivity(intent);
            }
        });
        mBinding.icSettingAddress.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), ShopAddressListActivity.class));
            }
        });
        mBinding.icSettingOrder.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                startActivity(new Intent(getActivity(), OrderListActivity.class));
            }
        });
        mBinding.icSettingSex.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改性别", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入性别")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                if ("男".equals(inputStr) || "女".equals(inputStr)) {
                                    App.getInstance().user.setSex(inputStr);
                                    userDao.update(App.getInstance().user);
                                    showToast("修改性别成功");
                                } else {
                                    showToast("请输入正确性别");
                                }
                                return false;
                            }
                        })
                        .show();
            }
        });
        mBinding.icChangePassword.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改密码", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入新密码")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                App.getInstance().user.setPassword(inputStr);
                                userDao.update(App.getInstance().user);
                                showToast("修改密码成功");
                                return false;
                            }
                        })
                        .show();
            }
        });
        mBinding.icVersion.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                MessageDialog.build()
                        .setTitle("提示")
                        .setMessage("当前已经是最新版本")
                        .setOkButton("确定")
                        .show();
            }
        });

        // 设置手机号
        mBinding.icSettingPhone.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改手机号", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入手机号")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                if (!Utils.isPhoneNumber(inputStr)) {
                                    showToast("手机号格式错误");
                                    return false;
                                }
                                userDao.update(App.getInstance().user);
                                App.getInstance().user.setPhone(inputStr);
                                showToast("修改手机号成功");
                                return false;
                            }
                        })
                        .show();
            }
        });

        // 设置昵称
        mBinding.icChangeName.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改昵称", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入昵称")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                if (TextUtils.isEmpty(inputStr)) {
                                    showToast("输入不能为空");
                                    return false;
                                }
                                App.getInstance().user.setName(inputStr);
                                mBinding.tvName.setText(inputStr);
                                userDao.update(App.getInstance().user);
                                showToast("修改昵称成功");
                                return false;
                            }
                        })
                        .show();
            }
        });

        // 设置邮箱
        mBinding.icChangeEmail.setMenuOptionsClickListener(new MenuOptionsView.MenuOptionsClickListener() {
            @Override
            public void layoutClick() {
                new InputDialog("修改邮箱", "", "确定", "取消", "")
                        .setCancelable(false)
                        .setTitleIcon(R.mipmap.logo)
                        .setInputHintText("输入邮箱")
                        .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                            @Override
                            public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                                if (!Utils.isEmailAddress(inputStr)) {
                                    showToast("输入邮箱格式错误");
                                    return false;
                                }
                                App.getInstance().user.setEmail(inputStr);
                                userDao.update(App.getInstance().user);
                                showToast("修改输入邮箱成功");
                                return false;
                            }
                        })
                        .show();
            }
        });

        final String[] permissions;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2) {
            permissions = new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            permissions = new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }
        if (PermissionUtil.checkAndRequestPermissionsInActivity(getActivity(),
                permissions)) {
            preLoadAlbums();
        }
        mBinding.imageHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyPhotos
                        .createAlbum(getActivity(), true, true, ImageEngine.getInstance())
                        .setCount(1)
                        .setFileProviderAuthority("com.example.shopapp.fileprovider")
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                if (photos.size() > 0) {
                                    String path = photos.get(0).path;
                                    Glide.with(getActivity()).load(path).into(mBinding.imageHead);
                                    App.getInstance().user.setHead_url(path);
                                    userDao.update(App.getInstance().user);
                                }
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }
        });
        mBinding.btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                meModel.logout();
            }
        });
    }

    /**
     * 预加载相册扫描，可以增加点速度，写不写都行
     * 该方法如果没有授权读取权限的话，是无效的，所以外部加不加权限控制都可以，加的话保证执行，不加也不影响程序正常使用。
     */
    private void preLoadAlbums() {
        EasyPhotos.preLoad(getActivity());
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull final String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        PermissionUtil.onPermissionResult(getActivity(), permissions, grantResults,
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        preLoadAlbums();
                    }

                    @Override
                    public void onShouldShow() {
                    }

                    @Override
                    public void onFailed() {
                    }
                });
    }
}


